<?php

class model extends kernel 
{
	protected $pdo;//数据库
	protected $table;//数据库表名
	protected $id;//记录ID
	private $input;
	
	public $where;
	public $field;
	
	public function __construct($table,$id) {
		parent::__construct();	
		$this->table = $table;
		$this->id = $id;
		$this->pdo = $this->dbConnect();//连接数据库
		$this->input = $this->loadLib('input');
		date_default_timezone_set('Asia/Shanghai');
	}
	
	/**
	 * 查询一条记录
	 *
	 * @param unknown_type $cond
	 * @param unknown_type $field
	 */
	public function find($cond,$field=null) {
		$field = $this->getField($field);
		
		if(!empty($cond)) {
			$condition = $this->getCondition($cond);//组合where条件		
			$query = "SELECT $field FROM $this->table WHERE $condition";
			$stmt = $this->pdo->prepare($query);//准备查询语句
			$stmt->execute(array_values($cond));//执行查询
			return $stmt->fetch(PDO::FETCH_OBJ);
		}
	}
	/**
	 * 获取查询的字段
	 *
	 * @param  $field
	 * @return 
	 */
	protected function getField($field) {
		if(empty($field)) return $this->id;
		if(is_array($field)) return join(', ',$field);
		if(is_string($field)) return $field;
	}
	/**
	 * 获取查询数据库的条件
	 *
	 * @param unknown_type $condition
	 * @param unknown_type $arg
	 */
	private function getCondition($condition,$arg='AND') {
		if(empty($condition)) return false;
		
		if(is_array($condition)) {
			$count = 0;
			foreach ($condition as $key=>$value) {
				if($count !== 0) {
					$cond .= " $arg $key = ?";
				} else {
					$cond = "$key = ?";
				}
				$count++;
			}
			return $cond;
		}
		
		if(is_string($condition)) return $condition;
	}
	
	public function findAll($cond,$field=null,$arg=null){
		$field = $this->getField($field);
		
		if(!empty($cond)) {
			$condition = $this->getCondition($cond);
			$query = "SELECT $field FROM $this->table WHERE $condition";
			if(is_array($cond)){
				$stmt = $this->pdo->prepare($query);//准备查询语句
				$stmt->execute(array_values($cond));//执行查询
				return $stmt->fetchAll(PDO::FETCH_OBJ);
			}
			
			if(is_string($cond)) {
			
			}
		}
	}
	
	
	
	public function select($field,$table = null) {
		if(!empty($field)){
			return $this->field = join(', ',$field);
		} else {
			return $this->field = '* ';
		}
		
	}
	public function where($condition,$arg = 'AND') {
		if(!empty($condition) && is_array($condition)) {
			foreach ($condition as $key=>$value){
				$i = 0;
				if($i != 0) {
					$this->where .= "$arg $key = ?";
				} else {
					$this->where .=  "$key = ?";
				}
				$i++;
				
			}
			return $this->where;
		}
	}

	
}
?>